package service

import (
	"gitee.com/lzqysoft/framework/common/encrypt"
	"gitee.com/lzqysoft/framework/services/base/models"
	"gitee.com/lzqysoft/framework/common"
	"gitee.com/lzqysoft/framework/common/log"
)

const(
	DefaultPassword = "123456"
)

// RegistUser 添加用户
func RegistUser(account string)  error{

	pwd := encrypt.EncodeUserPwd(account, DefaultPassword)
	user := &models.User{}
	user.Account = account
	user.AccountKey = pwd

	err := models.AddUser(user)
	if err!= nil {
		return err
	}

	return nil
}

func Login(info map[string]interface{},reply *common.Result) {

	//log.Info(info)
	account, ok := info["account"]
	if !ok {
		log.Error("无法解析account参数")
		reply.Token = ""
		reply.Res = nil
		reply.Code = "0005"
		reply.Message = "无法解析参数，参数错误"
		return
	}
	pwd, ok := info["account_key"]
	if !ok {
		log.Error("无法解析account_key参数")
		reply.Token = ""
		reply.Res = nil
		reply.Code = "0005"
		reply.Message = "无法解析参数，参数错误"
		return
	}
	user, err := models.CheckLogin(account.(string), pwd.(string))
	if err != nil {
		log.Error(err)
		reply.Token = ""
		reply.Res = nil
		reply.Code = "0006"
		reply.Message = err.Error()
		return
	}
	reply.Token = GenerateToken(user.Id, user.OrganId)
	reply.Res = nil
	reply.Code = "0000"
	reply.Message = "success"
	//log.Info(reply)
}

func Info(token string, reply *common.Result) {
	user, org , token, err := models.GetJwt(token)
	if err != nil {
		log.Error(err)
		reply.Token = ""
		reply.Res = nil
		reply.Code = "0007"
		reply.Message = "无效的令牌"
		return
	}
	//dept ,group

	reply.Code = "0000"
	reply.Token = token
	reply.Message = ""
	reply.Res = make(map[string]interface{})
	reply.Res["user"] = user.Convert2Map()
	reply.Res["organ"] = org.Convert2Map()

}

func Menus(token string, reply *common.Result) {
	user, _ , token, err := models.GetJwt(token)
	if err != nil {
		log.Error(err)
		reply.Token = ""
		reply.Res = nil
		reply.Code = "0007"
		reply.Message = "无效的令牌"
		return
	}

	menus := models.GetMenusByUserIdAndGroupId(user.Id)

	reply.Code = "0000"
	reply.Token = token
	reply.Message = ""
	reply.Res = make(map[string]interface{})
	reply.Res["menus"] = menus
}